import csv
import argparse
import operator
import os.path
import re
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')



class qianQianBillRecord:
    # 日期
    comsumeDate = None
    # 分类
    comsumeKind = None
    # 类型
    comsumeType = None
    # 金额
    comsumePrice = None
    # 账户1
    discount1 = None
    # 账户2
    discount2 = None
    # 备注
    comment = None

    def __init__(self, date, kind, type, price, discount1, discount2, comment):
        self.comsumeDate = date
        self.comsumeKind = transforType((kind+comment).lower())
        self.comsumeType = type
        self.comsumePrice = price
        self.discount1 = discount1
        self.discount2 = discount2
        self.comment = comment

    @staticmethod
    def wepayToQian(qianjiRecords, wePayBillRecords):
        for record in wePayBillRecords:
            qianjiRecord = qianQianBillRecord(record.comsumeDate, record.comsumeKind,
                                              record.comsumeType, record.comsumePrice, "微信支付","",record.tradeMan+record.productName)
            qianjiRecords.append(qianjiRecord)

    @staticmethod
    def icbcToQian(qianjiRecords, icbcPayBillRecords):
        global qianjiRecord
        for record in icbcPayBillRecords:
            if record.incomeMoney != '':
                qianjiRecord = qianQianBillRecord(record.comsumeDate, record.comsumeKind, "收入", record.incomeMoney,
                                                  "工商银行", "", record.comsumeDescription)
            elif record.spendMoney != '' :
                qianjiRecord = qianQianBillRecord(record.comsumeDate, record.comsumeKind, "支出", record.spendMoney,
                                                  "工商银行", "", record.comsumeDescription+record.comsumeMan)
            qianjiRecords.append(qianjiRecord)

    @staticmethod
    def alipayToQian(qianjiRecords, alipayBillRecords):
        for aliRecord in alipayBillRecords:
            qianjiRecord = qianQianBillRecord(aliRecord.comsumeDate, aliRecord.comsumeKind, aliRecord.comsumeType,aliRecord.comsumePrice,
                                              "支付宝", "", aliRecord.comsumeKind +"-"+aliRecord.tradeStatement)
            qianjiRecords.append(qianjiRecord)

    @staticmethod
    def writetoCsv(csvFile, qianjiRecords):
        header = ["时间","分类","类型","金额",	"账户1",	"账户2","备注","账单标记","账单图片"]
        with open(csvFile, "w", encoding="utf-8-sig") as f:
            writer = csv.writer(f)
            writer.writerow(header)
            for record in qianjiRecords:
                writer.writerow([record.comsumeDate,
                                 record.comsumeKind,
                                 record.comsumeType,
                                 record.comsumePrice,
                                 record.discount1,
                                 record.discount2,
                                 record.comment])

class alipayBillRecord:
    # 类型
    comsumeType = None
    # 交易对方
    tradeAccount = None
    # 对方账号
    tradeAliAccount = None
    #  商品说明
    tradeStatement = None
    #  收/付款方式
    paryOrincomeWay = None
    # 金额
    comsumePrice = None
    # 交易状态
    tradeStatus = None
    # 交易分类
    tradeKind = None
    # 交易订单
    tradeOrder = None
    # 商家订单号
    merchantOrder = None
    # 交易时间
    comsumeDate = None

    def __init__(self, date, kind,tradeAccount,type, way, comsumePrice, tradeStatement):
        self.comsumeDate = date
        self.comsumeKind = kind
        self.comsumeType = type
        self.tradeAccount = tradeAccount
        self.paryOrincomeWay = way
        self.comsumePrice = comsumePrice
        self.tradeStatement = tradeStatement

class wePayBillRecord:
    # 交易时间
    comsumeDate = None
    # 交易订单交易类型
    tradeKind = None
    # 交易对方
    tradeMan = None
    # 商品
    productName = None
    # 收/支
    comsumeType = None
    # 金额
    comsumePrice = None
    # 支付方式
    comsumeWay = None
    # 当前状态
    comsumeStatus = None

    def __init__(self, date, kind, man, product, type, comsumePrice, comsumeWay, comsumeStatus):
        self.comsumeDate = date
        self.comsumeKind = kind
        self.tradeMan = man
        self.productName = product
        self.comsumeType = type
        self.comsumePrice = comsumePrice
        self.comsumeWay = comsumeWay
        self.comsumeStatus = comsumeStatus

class icbcBillRecord:
    # 交易日期
    comsumeDate = None
    # * 摘要(消费、跨行汇款)
    comsumeKind = None
    # * 交易场所（收款人）
    comsumeDescription = None
    # * 记账金额（收入）
    spendMoney = None
    # * 记账金额（支出）
    incomeMoney = None
    comsumeMan = None

    def __init__(self, date, kind, description, spendMoney, incomeMoney, man):
        self.comsumeDate = dropSpaceandTab(date)
        self.comsumeKind = dropSpaceandTab(kind)
        self.comsumeDescription = dropSpaceandTab(description)
        self.spendMoney = dropSpaceandTab(spendMoney)
        self.incomeMoney = dropSpaceandTab(incomeMoney)
        self.comsumeMan = dropSpaceandTab(man)

def dropSpaceandTab(string):
    return string.replace(" ", "").replace("\t", "")

def transforType(memo):
    # 收入
    salary = ["工资", "华为"]
    redpocket = ["红包"]
    stock = ["余额宝","批量业务"]
    dropback = ["退款"]

    for keyword in salary:
        if keyword in memo:
            return "工资"

    for keyword in dropback:
        if keyword in memo:
            return "退款"

    for keyword in redpocket:
        if keyword in memo:
            return "红包"

    for keyword in stock:
        if keyword in memo:
            return "分红"

    # 支出
    travel = ["旅游"]
    social = ["红包", "群收款"]
    learn = ["书"]
    makeup = ["美容"]
    medical = ["药", "医院", "医疗"]
    entertain = []
    sport = ["球"]
    subscribe = ["电信", "icloud", "applemusic", "艾珀", "Apple Music", "App Store","App Store & Apple Music","music"]
    traffic = ["汽车", "油", "铁路", "高速", "滴滴", "打车", "高德", "停车费"]
    eat = ["必胜客", "全家", "井冈印象", "麦当劳", "餐", "便利店", "嘉旺", "饭", "火锅", "酒楼", "酒家", "蛋糕","烤鱼","排挡",
           "老碗会", "金拱门", "食品", "美团", "McDonaldsChina", "面", "米粉", "美食", "香锅", "海鲜", "全家",
,"Lawson", "有家", "美食", "餐厅", "餐饮", "便利店", "探炉", "嘉荣", "美味", "蜜雪冰城", "钱大妈"]
    insurance = ["保险"]
    shop = ["拼多多", "京东", "淘宝", "唯品会", "超市", "苏宁" ,"抖音电商"]
    other = ["二维码", "条码", "顺丰", "邮政", "圆通", "EMS", "丰巢"]
    rent = ["房租", "水电"]

    for keyword in eat:
        if keyword in memo:
            return "三餐"

    for keyword in rent:
        if keyword in memo:
            return "房租"

    for keyword in subscribe:
        if operator.contains(memo, keyword):
            return "话费网费"
        
    for keyword in makeup:
        if keyword in memo:
            return "美妆"

    for keyword in shop:
        if keyword in memo:
            return "购物"

    for keyword in learn:
        if keyword in memo:
            return "学习"

    for keyword in traffic:
        if keyword in memo:
            return "交通"

    for keyword in travel:
        if keyword in memo:
            return "旅行"

    for keyword in medical:
        if keyword in memo:
            return "医疗"

    for keyword in insurance:
        if keyword in memo:
            return "保险"

    for keyword in sport:
        if keyword in memo:
            return "运动"

    for keyword in social:
        if keyword in memo:
            return "人情"

    for keyword in other:
        if keyword in memo:
            return "其他"

    return "其他"

def find_files_with_regex(folder_path, pattern):
    match_files = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if re.match(pattern, file):
                match_files.append(os.path.join(root, file))
    if(len(match_files) != 1):
        raise ValueError("文件数量不正常，找到{}个文件。".format(len(match_files)))
    return match_files[0]


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-F', type=str, default=None)
    args = parser.parse_args()
    folder = args.F
    icbcRecords = []
    alipayRecords = []
    wepayRecords = []
    qianjiRecords = []


    # 读取工商银行记录
    icbcFile = find_files_with_regex(folder, pattern=re.compile(r'^hisdetail\d{13}.csv$'));
    with open(icbcFile, "r", encoding="utf-8") as icbcCsv:
        reader = csv.reader(icbcCsv)
        count = 0

        for row in reader:
            if count > 6 and len(row) == 14:
                icbcRecords.append(icbcBillRecord(row[0], row[1], row[2], row[9], row[8], row[12]))
            count += 1
    
    # 读取支付宝记录
    alipayFile = find_files_with_regex(folder, pattern=re.compile(r'^alipay_record_.*\.csv$'))
    with open(alipayFile, "r", encoding="gbk") as alipayCsv:
        reader = csv.reader(alipayCsv)
        count = 0

        for row in reader:
            if count > 0 and len(row) == 13 and (row[7] == '余额宝' or row[7] == '余额'):
                alipayRecord = alipayBillRecord(row[0], row[1], row[2], row[5], row[7], row[6], row[4])
                alipayRecords.append(alipayRecord)
            count += 1

    # 读取微信支付记录
    wepayFile = find_files_with_regex(folder, pattern=re.compile(r'^微信支付账单.*\.csv$'))
    with open(wepayFile, "r", encoding="utf-8") as wepayCsv:
        reader = csv.reader(wepayCsv)
        count = 0
        for row in reader:
            if count > 16 and len(row) == 11 and ((row[4] == '支出' and row[6] == '零钱') or (row[4] == '收入' and row[6]== '/')):
                wepayRecord = wePayBillRecord(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])
                wepayRecords.append(wepayRecord)
            count += 1

    # 读取支付宝转为钱迹对象
    print('开始写入支付宝记录...')
    qianQianBillRecord.alipayToQian(qianjiRecords, alipayRecords)
    print('支付宝记录写入成功！')
    # 读取微信转为钱迹对象
    print('开始写入微信记录...')
    qianQianBillRecord.wepayToQian(qianjiRecords, wepayRecords)
    print('微信支付写入成功！')
    # 读取工商转为钱迹对象
    print('开始写入工商银行记录...')
    qianQianBillRecord.icbcToQian(qianjiRecords, icbcRecords)
    print('工商银行记录写入成功！')
    # 求交集，写入钱迹
    csvFile = "./"+folder+"/"+folder+".csv"
    qianQianBillRecord.writetoCsv(csvFile, qianjiRecords)
